
/**
 * 本组件核心思路是
 * 我们要通过缓存容器去创建OldComponent对应的真实DOM，并且进行缓存
 * 即使这个OldComponent被销毁了，缓存还可以保留
 * 以后这个OldComponent再次渲染的时候，可以复用上次的缓存就可以了
 */

import React, { useContext, useRef,useEffect } from "react";
import * as cacheTypes from './cache-types';
import CacheContext from './CacheContext';

function withKeepAlive(OldComponent, { cacheId = window.location.pathname,scroll=false }) {
    return function(props){
        const {mount, cacheStates,dispatch,handleScroll } = useContext(CacheContext);
        const ref = useRef(null);
        useEffect(()=>{
            if(scroll){
               ref.current.addEventListener('scroll', handleScroll.bind(null, cacheId),true); //监听捕获阶段
            }
        },[handleScroll])
        useEffect(()=>{
            let cacheState = cacheStates[cacheId];
            if(cacheState&&cacheState.doms && cacheState.status !== cacheTypes.DESTROY){ //如果真实dom已经ok了
                let doms = cacheState.doms;
                doms.forEach(dom=>ref.current.appendChild(dom));
                if(scroll){
                    doms.forEach((dom)=>{
                        if (cacheState.scrolls[dom]){
                            dom.scrollTop = cacheState.scrolls[dom];
                        }
                    })
                }
            }else{
                mount({ cacheId, element: <OldComponent {...props} dispatch={dispatch}/> })
            }

        },[mount, props])
        return (
        <div id={`keepalive_${cacheId}`} ref = {ref}>
            
        </div>
        )
    }
}   
export default withKeepAlive;
